package org.ilovecode.utils {
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	/**
	 * Class containing functions to load content.
	 * 
	 * @author Vjekoslav Ratkajec
	 */
	public class Utilities {
		
		private static var _inLoading:Boolean;
		private static var _toLoadList:Array;
		private static var _loadedList:Array;
		private static var _func:Function;
		
		/**
		 * Load data from URL as text, binary data, or URL-encoded variables.
		 * 
		 * @param	url		URL to load data from.
		 * @param	func	Function to call after content is loaded.
		 */
		public static function loadURL(url:String, func:Function):void {
			var req:URLRequest = new URLRequest(url);
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, func);
			loader.addEventListener(IOErrorEvent.IO_ERROR, loader_IOError);
			try {
				loader.load(req);
			} catch (e:Error) {
				throw e;
			}
		}
		
		/**
		 * Load SWF files or image (JPG, PNG, or GIF) files from URL.
		 * 
		 * @param	url		URL to load data from.
		 * @param	func	Function to call after content is loaded.
		 */
		public static function loadContent(url:String, func:Function):void {
			var req:URLRequest = new URLRequest(url);
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, func);
			loader.addEventListener(IOErrorEvent.IO_ERROR, loader_IOError);
			try {
				loader.load(req);
			} catch (e:Error) {
				throw e;
			}
		}
		
		public static function loadMultipleURL(list:Array, func:Function):void
		{
			//If loading is in progress, exit (doesn't support multiple loading)
			if (_inLoading)
				return;
			else
				_inLoading = true;
			
			//If array is empty, return null
			if (list.length <= 0)
				func(null);
			
			//Save recieved data
			_toLoadList = list;
			_func = func;
			_loadedList = new Array();
			
			//Start loading
			loadNextURL();
		}
		
		private static function loadNextURL():void 
		{
			//Load next
			loadURL(String(_toLoadList[0]), loadSingleURL_Complete);
			//Remove item from loading array
			_toLoadList.splice(0,1);
		}
		
		private static function loadSingleURL_Complete(event:Event):void
		{
			_loadedList.push(event.target.data);
			
			if (_toLoadList.length > 0)
				loadNextURL();
			else
				_func(_loadedList);
		}
		
		/**
		 * Error while loading.
		 * 
		 * @param	event	IOError has occured.
		 * @private
		 */
		private static function loader_IOError(event:IOErrorEvent):void {
			trace("Unable to load from supplied URL");
		}
		
	}
	
}